GO 中如何在逐行高效地逐行读取文件 您所在的位置:网站首页 go 读取文本kv GO 中如何在逐行高效地逐行读取文件

GO 中如何在逐行高效地逐行读取文件

2023-10-01 05:23| 来源: 网络整理| 查看: 265

包和必要的 Import Go 中对文件逐行读取 Go 中逐行读取文件的完整代码 在 Go 中配置 Scanner 行为 GO 中如何在逐行高效地逐行读取文件

文件 I/O,特别是对文件的读写是编程语言中重要的功能。通常,你需要逐行读取文件。GO 提供了 bufio 软件包,该软件包基本上实现了缓冲的 I/O。bufio 提供有用的类型和函数,特别是用于读取和写入文本文件。

Ezoic 包和必要的 Import package main import( "fmt" "bufio" "log" "os" ) Ezoic

我们将需要从 GO 标准库中导入多个文件:-

OS - 用于独立于平台的 OS 函数接口 FMT - 实现格式化的 I/O 函数 log - 标准日志记录包 bufio - 支持缓冲的 I/O Go 中对文件逐行读取

在读取文件之前,首先需要使用 os.Open() 函数将其打开,该函数返回指向文件的指针类型。代码段中显示的 test.txt 文件需要已经存在在系统中(将路径放置到文件所在的位置)。

Ezoic

bufio.NewScanner(file) 函数返回 scanner 类型,该类型中的函数支持读取文件。

要逐行读取文件,我们需要使用两种在新的 Scanner 的方法-Scan,它会将 Scanner 前进到新的符记(在本例中为新行),和 Text(或 Byte)读取调用 Scan 时生成的最新符记。

如果在读取文件时遇到任何错误,可以通过在新的 Scanner 上调用 Err() 方法来处理这些错误,该方法将返回 Scanner 遇到的第一个非文件结尾错误。

func main(){ // open the file file, err := os.Open("test.txt") //handle errors while opening if err != nil { log.Fatalf("Error when opening file: %s", err) } fileScanner := bufio.NewScanner(file) // read line by line for fileScanner.Scan() { fmt.Println(fileScanner.Text()) } // handle first encountered error while reading if err := fileScanner.Err(); err != nil { log.Fatalf("Error while reading file: %s", err) } file.Close() } Go 中逐行读取文件的完整代码

下面提供了 main.go 中用于逐行读取文件的完整代码。

你需要输入:

$ go run main.go

在终端中运行程序。

package main import ( "bufio" "fmt" "log" "os" ) func main() { // open the file file, err := os.Open("test.txt") //handle errors while opening if err != nil { log.Fatalf("Error when opening file: %s", err) } fileScanner := bufio.NewScanner(file) // read line by line for fileScanner.Scan() { fmt.Println(fileScanner.Text()) } // handle first encountered error while reading if err := fileScanner.Err(); err != nil { log.Fatalf("Error while reading file: %s", err) } file.Close() } 在 Go 中配置 Scanner 行为

Scanner 类型具有 Split 函数,该函数接受 SplitFunc 函数来确定 Scanner 如何拆分给定的字节片。默认的 SplitFunc 是 ScanLines,它将返回文本的每一行,并删除行尾标记。

例如,我们可以使用单词进行拆分,如下面的代码片段所示:-

scanner.Split(bufio.ScanWords) //configure how the scanner behaves


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有